﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook.Web;
using WhsFacebook.Net.Web.Database;

namespace WhsFacebook.Net.Web.Facebook
{
    public partial class FromWhs : CanvasFBMLBasePage
    {
        protected Guid _whsInstanceId;

        public FromWhs()
        {
            this.RequireLogin = true;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // prepare
            var doAssign = FacebookConverter.ToBoolean(this.Request.Params["assign"]);
            var defMaster = (DefaultMaster)this.Master;
            var userId = defMaster.FacebookVisit.UserId;
            var whsId = defMaster.FacebookVisit.WhsInstanceId;

            // page cannot be called without whs id!
            if (!whsId.HasValue)
            {
                // show error
                this.noWhsId.Visible = true;

                return;
            }

            _whsInstanceId = whsId.Value;

            // check if the WHS is already associated
            using (var ent = new Database.WhsFacebookEntities())
            {
                var assoc = (
                    from id in ent.FacebookInstanceMappings
                    where id.FacebookUserId == userId
                    select id
                    ).FirstOrDefault();

                if (doAssign)
                {
                    // perform the association
                    if (assoc != null)
                    {
                        ent.DeleteObject(assoc);
                    }

                    ent.AddToFacebookInstanceMappings(new DbFacebookInstanceMapping()
                    {
                        FacebookUserId = userId,
                        InstanceId = whsId.Value,
                    });

                    ent.SaveChanges();

                    this.redirectToHome.Visible = true;
                }
                else
                {
                    // association required?
                    if ((assoc == null) || (assoc.InstanceId != whsId.Value))
                    {
                        // no association found
                        // ask the user for association
                        this.assignForm.Visible = true;
                    }
                    else
                    {
                        // there is already an association
                        // redirect to start page
                        this.redirectToHome.Visible = true;
                    }
                }
            }
        }
    }
}